#include "util.h"
#include <QDebug>
#include <QFileInfo>
#include <QRandomGenerator>

bool Util::writeInit(const QString& path, const QString& user_key, const QString& user_value)
{
    try {
        QSettings config(path, QSettings::IniFormat);
        config.beginGroup("config");
        config.setValue(user_key, user_value);
        config.endGroup();
        config.sync();
        return config.status() == QSettings::NoError;
    } catch (...) {
        return false;
    }
}

bool Util::readInit(const QString& path, const QString& user_key, QString& user_value)
{
    try {
        QSettings config(path, QSettings::IniFormat);
        user_value = config.value(QString("config/") + user_key).toString();
        return true;
    } catch (...) {
        user_value.clear();
        return false;
    }
}

QString Util::getConfigPath()
{
    QString appDir = QCoreApplication::applicationDirPath();
    return QDir(appDir).absoluteFilePath("user.ini");
}

QString Util::getUserConfigPath()
{
    QString dataPath = getApplicationDataPath();
    return QDir(dataPath).absoluteFilePath("user.ini");
}

QString Util::getApplicationDataPath()
{
    QString appName = QCoreApplication::applicationName();
    if (appName.isEmpty()) {
        appName = "LongImageReader";
    }

    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    if (dataPath.isEmpty()) {
        // 备用路径
        dataPath = QDir::homePath() + "/." + appName;
    }

    return ensureDirectoryExists(dataPath);
}

QString Util::ensureDirectoryExists(const QString& path)
{
    QDir dir(path);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    return dir.absolutePath();
}

QString Util::generateRandomString(int length)
{
    const QString chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    QString result;
    result.reserve(length);

    for (int i = 0; i < length; ++i) {
        int index = QRandomGenerator::global()->bounded(chars.length());
        result.append(chars.at(index));
    }

    return result;
}

QString Util::formatBytes(qint64 bytes)
{
    const QStringList units = {"B", "KB", "MB", "GB", "TB"};
    double size = bytes;
    int unitIndex = 0;

    while (size >= 1024.0 && unitIndex < units.size() - 1) {
        size /= 1024.0;
        unitIndex++;
    }

    return QString::number(size, 'f', 2) + " " + units[unitIndex];
}

bool Util::fileExists(const QString& filePath)
{
    return QFileInfo::exists(filePath);
}

bool Util::createDirectory(const QString& dirPath)
{
    return QDir().mkpath(dirPath);
}

bool Util::removeDirectory(const QString& dirPath)
{
    QDir dir(dirPath);
    return dir.removeRecursively();
}